package com.threeti.mecool.core.application.acl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import com.threeti.mecool.core.domain.model.acl.OrgnizationEmployee;
import com.threeti.mecool.core.domain.model.acl.SystemRole;
import com.threeti.mecool.core.domain.model.acl.User;

public class UserAdapter implements UserDetails {
  private final User user;

  public UserAdapter(User user) {
    this.user = user;
  }

  @Override
  public Collection<GrantedAuthority> getAuthorities() {
    Set<SystemRole> systemRoles = user.getSystemRoles();
    if (CollectionUtils.isEmpty(systemRoles))
      return Collections.emptyList();

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for (SystemRole systemRole : systemRoles) {
      authorities.add(new SimpleGrantedAuthority(systemRole.getName()));
    }
    return authorities;
  }

  @Override
  public String getPassword() {
    return user.getPassword();
  }

  @Override
  public String getUsername() {
    return user.getLoginName();
  }

  @Override
  public boolean isAccountNonExpired() {
    return true;
  }

  @Override
  public boolean isAccountNonLocked() {
    return true;
  }

  @Override
  public boolean isCredentialsNonExpired() {
    return true;
  }

  @Override
  public boolean isEnabled() {
    return true;
  }

  public User getUser() {
    //保险处理，万一无法关联企业员工，不让页面报错->
    if (user.getEmployee() == null) {
      OrgnizationEmployee orgEmp = new OrgnizationEmployee();
      orgEmp.setTitleWithinTheOrg("");
      user.setEmployee(orgEmp);
    }
    //<-
    return user;
  }
}
